package com.fuful.service;

import com.fuful.domian.*;
import com.fuful.mappers.JyInfoMapper;
import com.fuful.mappers.OrdersDetailsMapper;
import com.fuful.mappers.OrdersMapper;
import com.fuful.utils.MybatisUtil;
import com.fuful.utils.OrderTools;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class OrdersService {

    private SqlSession sqlSession = MybatisUtil.getSqlSession();

    public boolean createUsersOrder(Users users, Map<Products,Integer> cart){
        //1.生成订单流水
        String orderid = OrderTools.createOrderCode();
        //2.生成订单对象
        Orders orders = new Orders();
        orders.setOrderid(orderid);
        orders.setUid(users);
        //生成获得总价格以及订单明细集合
        float totalPrice = 0f;
        List<OrdersDetails> details = new ArrayList<>();
        Set<Products> keys = cart.keySet();
        for (Products p: keys) {
            //计算总价格
            Integer num = cart.get(p);
            totalPrice = totalPrice + p.getPprice() * num.intValue();
            //生成每一个订单明细
            OrdersDetails detail = new OrdersDetails();
            detail.setOrderid(orders);
            detail.setPid(p);
            detail.setNum(num.intValue());
            details.add(detail);
        }
        orders.setDetails(details);
        orders.setOrderprice(totalPrice);
        //创建JyInfo对象
        JyInfo jyInfo = new JyInfo();
        jyInfo.setJycode(OrderTools.createOrderCode());
        jyInfo.setJytype(1);
        jyInfo.setJymomey(totalPrice);
        //调用持久层操作
        OrdersMapper ordersMapper = sqlSession.getMapper(OrdersMapper.class);
        OrdersDetailsMapper ordersDetailsMapper = sqlSession.getMapper(OrdersDetailsMapper.class);
        JyInfoMapper jyInfoMapper = sqlSession.getMapper(JyInfoMapper.class);
        int flag = ordersMapper.addOrder(orders);
        int flag2 = ordersDetailsMapper.addOrdersDetails(details);
        int flag3 = jyInfoMapper.addJyInfo(jyInfo);
        if((flag+flag2+flag3) == 2+details.size()){
            sqlSession.commit();
            return true;
        }else {
            sqlSession.rollback();
        }

        return false;
    }
}
